require("dotenv").config({ path: "./.env" });
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("./db.json");

/* 环境变量 */
const {
  SERVER_HOST = "localhost",
  SERVER_PORT = 3000,
  SERVER_STATIC_DIR = "./public ",
  ROUTE_BASE_PATH = "/v1",
  SWAGGER_UI_PATH = "/swagger",
} = process.env;

(async () => {

  /* json-server 配置 */
  server.use(
    jsonServer.defaults({
      watch: true,
      static: SERVER_STATIC_DIR,
      bodyParser: true,
    })
  );

  /* swagger */
  await require("./middleware/swagger.middleware")({
    server,
    env: process.env,
  });

  /* 统一返回格式 */
  router.render = (req, res) => {
    // 删除返回信息中的密码
    if (res.locals.data.password) delete res.locals.data.password;
    const r = {
      status: res.statusCode,
      success: true,
      data: res.locals.data,
    };
    if (res.statusCode === 404) {
      r.status = "Not Found";
      r.success = false;
      r.message = "resource not found";
      r.data = "";
    }
    res.send(r);
  };
  /* 路由 */
  server.use(ROUTE_BASE_PATH, [

    // AUTH
    await require("./middleware/auth.middleware")({
      db: router.db,
      env: process.env,
    }),

    // ACL
    // await require("./middleware/acl.middleware")({
    //   db: router.db,
    //   env: process.env,
    // }),

    // 自定义路由
    require("./routes/users")(),

    // ACL规则
    require("./routes/rules")(),

    // 统一设置更新时间和添加时间
    (req, res, next) => {
      if (req.method === "POST") {
        req.body.ctime = Date.now();
        req.body.mtime = Date.now();
      }
      if (req.method === "PUT" || req.method === "PATCH") {
        req.body.mtime = Date.now();
      }
      next();
    },
    // json-server 路由
    router,
  ]);

  /* 全局错误捕捉 */
  server.use((err, req, res, next) => {
    // UnauthorizedError Unauthorized
    if (err.name === "UnauthorizedError")
      return res.status(err.status).send({
        status: err.status,
        success: false,
        message: "Invalid token",
      });

    if (err.name === "custom")
      return res.status(400).json({
        status: 400,
        success: false,
        message: err.message,
      });

    res.status(err.status || 500).json({
      status: err.status,
      success: false,
      message: err.message,
    });
  });

  /* 启动服务 */
  server.listen(SERVER_PORT, SERVER_HOST, () => {
    console.table({
      swagger: `http://${SERVER_HOST}:${SERVER_PORT}${ROUTE_BASE_PATH}${SWAGGER_UI_PATH}`,
    });
  });
})();
